<template>
  <div v-loading="pageLoading" class="train_step_fee">
    <div v-for="(item, index) in charges" :key="index">
      <div v-if="item.code === 'Train'" class="box_wrap gl_mb_10">
        <div style="margin-bottom: 10px" class="box_wrap_title">{{ item.name }}</div>
        <el-table size="small" :data="item.items" style="width: 100%;" class="gl_table_noBorder gl_mb_15">
          <el-table-column prop="name" label="培训科目" />
          <el-table-column prop="amount" label="价格" width="280">
            <template slot-scope="{ row }">
              ￥{{ formatMoney(row.amount) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="table_bottom">
          <span class="count">共计报名{{ item.itemsCount }}项</span>
          <span class="price">合计：<span class="price_color">￥{{ formatMoney(item.categoryAmount) }}</span></span>
        </div>
      </div>

      <div v-if="item.code === 'Exam'" class="box_wrap gl_mb_10">
        <div style="margin-bottom: 10px" class="box_wrap_title">{{ item.name }}</div>
        <el-table size="small" :data="item.items" style="width: 100%;" class="gl_table_noBorder gl_mb_15">
          <el-table-column prop="name" label="考试科目" />
          <el-table-column prop="amount" label="价格" width="280">
            <template slot-scope="{ row }">
              ￥{{ formatMoney(row.amount) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="table_bottom">
          <span class="count">共计报名{{ item.itemsCount }}项</span>
          <span class="price">合计：<span class="price_color">￥{{ formatMoney(item.categoryAmount) }}</span></span>
        </div>
      </div>

      <div v-if="item.code === 'Hotel'" class="box_wrap gl_mb_10">
        <div style="margin-bottom: 10px" class="box_wrap_title">{{ item.name }}</div>
        <el-table size="small" :data="item.items" style="width: 100%;" class="gl_table_noBorder gl_mb_15">
          <el-table-column prop="name" label="酒店名称" />
          <el-table-column prop="roomType" label="房型" />
          <el-table-column prop="dinnerType" label="餐食" />
          <el-table-column prop="dayCount" label="天数" />
          <el-table-column prop="comment" label="备注" />
          <el-table-column prop="amount" label="价格">
            <template slot-scope="{ row }">
              ￥{{ formatMoney(row.amount) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="table_bottom">
          <span class="count">共计住宿费{{ item.itemsCount }}项</span>
          <span class="price">合计：<span class="price_color">￥{{ formatMoney(item.categoryAmount) }}</span></span>
        </div>
      </div>

      <div v-if="item.code === 'Membership'" class="box_wrap gl_mb_10">
        <div style="margin-bottom: 10px" class="box_wrap_title">{{ item.name }}</div>
        <el-table size="small" :data="item.items" style="width: 100%;" class="gl_table_noBorder gl_mb_15">
          <el-table-column prop="name" label="会员类型" />
          <el-table-column prop="yearCount" label="年限" />
          <el-table-column prop="amount" label="价格">
            <template slot-scope="{ row }">
              ￥{{ formatMoney(row.amount) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="table_bottom">
          <span class="count">共计续费{{ item.itemsCount }}项</span>
          <span class="price">合计：<span class="price_color">￥{{ formatMoney(item.categoryAmount) }}</span></span>
        </div>
      </div>

      <div v-if="item.code === 'Other'" class="box_wrap gl_mb_10">
        <div style="margin-bottom: 10px" class="box_wrap_title">{{ item.name }}</div>
        <el-table size="small" :data="item.items" style="width: 100%;" class="gl_table_noBorder gl_mb_15">
          <el-table-column prop="name" label="费用名称" />
          <el-table-column prop="amount" label="价格">
            <template slot-scope="{ row }">
              ￥{{ formatMoney(row.amount) }}
            </template>
          </el-table-column>
        </el-table>
        <div class="table_bottom">
          <span class="count">共计续费{{ item.itemsCount }}项</span>
          <span class="price">合计：<span class="price_color">￥{{ formatMoney(item.categoryAmount) }}</span></span>
        </div>
      </div>
    </div>

    <div v-show="calculateEntryOrder.charges && calculateEntryOrder.charges.length" class="box_wrap order_summary gl_mb_10 gl_clear">
      <div style="margin-right: 120px" class="gl_fl">
        <div v-for="(item, index) in charges" :key="index" class="gl_mb_10">
          <span class="order_summary_label">{{ item.name }}</span>
          <span class="order_summary_price">{{ formatMoney(item.categoryAmount) }} 元</span>
        </div>
        <div>
          <span class="order_summary_label">已缴纳费用</span>
          <span class="order_summary_price">{{ formatMoney(calculateEntryOrder.paidAmount) }} 元</span>
        </div>
      </div>
      <div class="gl_fl">
        <span class="order_summary_label">合计</span>
        <span class="order_summary_price gl_color_total">{{ formatMoney(calculateEntryOrder.totalAmount - calculateEntryOrder.paidAmount) }}元</span>
      </div>
    </div>

    <div v-show="!pageLoading && !calculateEntryOrderSuccess" class="no_hotel">
      <div>
        支付遇到问题？请及时联系主办方处理，以便完成报名。
      </div>
      <div>
        联系人及电话：{{ trainInfo.contactPerson }} {{ trainInfo.contactPhoneNumber }}
      </div>
    </div>

    <el-row>
      <el-col class="step_btn" :span="24" align="center">
        <el-button @click="onPrevStep">上一步</el-button>
        <el-button type="primary" :disabled="!calculateEntryOrderSuccess" :loading="nextLoading" @click="clickPay()">去支付</el-button>
      </el-col>
    </el-row>

    <form id="form" ref="form" action="https://unipay.ydfuture.com/api/v1/trade/cashDesk" method="post" style="display:none">
      <input ref="pay_params" type="text" name="pay_params" value="">
      <button type="submit">提交</button>
    </form>

    <!-- 选择支付方式弹框 -->
    <el-dialog class="gl_dialog_TitleLine" title="选择支付方式" :visible.sync="dialogVisibleForPay" :close-on-click-modal="false" width="650px">
      <div v-loading="modalPayLoding" class="pay_type_list">
        <div class="pay_type_item pay_type_offline gl_clear" @click="clickPayOffline()">线下支付</div>
        <div class="pay_type_item pay_type_online gl_clear" @click="clickPayOnline()">线上支付</div>
      </div>
    </el-dialog>

    <el-dialog
      class="gl_dialog_TitleLine"
      title="线下收款账户信息"
      width="640px"
      :visible.sync="offlineDialogVisible"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <offline-pay-info :offline-data="offlineData" />
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="jumpToOrderCenter">前往订单中心</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import OfflinePayInfo from '@/components/OfflinePayInfo';

import {
  api_POST_TrainTrainningEntryCalculateEntryOrder,
  api_POST_TrainTrainningEntrySubmitOrder // 提交订单
} from '@/extend/api/trainswaggerApi/app.js';

import {
  api_GET_TradePersonalOrderCollectionCode, // 获取线下支付订单的收款码信息
  api_GET_TradePayOrderParameter // 获取支付订单的参数
} from '@/extend/api/swaggerApi/app';

import {
  Api_GET_TradePayOrderParameterQO
} from '@/lib/form/swaggerForm';

export default {
  components: {
    OfflinePayInfo
  },
  props: {
    // 传入的个人信息数据
    trainInfo: {
      type: Object,
      default() {
        return {};
      }
    },
    isShow: {
      type: Boolean(),
      default: false
    },
    requiredIdData: {
      type: Object,
      default() {
        return {};
      }
    },
    transferData: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data () {
    return {
      orderParameterQO: new Api_GET_TradePayOrderParameterQO(),
      pageLoading: true,
      nextLoading: false,
      vo: {},
      charges: [],
      calculateEntryOrder: {},
      dialogVisibleForPay: false,
      isOnlinePayment: false,
      modalPayLoding: false,
      offlineDialogVisible: false,
      offlineData: {},
      orderNo: '',
      calculateEntryOrderSuccess: false // calculateEntryOrder 是否请求成功
    };
  },
  watch: {
    isShow: {
      immediate: true,
      handler(val) {
        if (val) {
          const _vo = {
            trainningId: this.trainInfo.id,
            registerId: this.requiredIdData.registerId,
            subjectIds: this.transferData.subjectIds,
            isOnlinePayment: true
          };

          if (this.trainInfo.setting.includeHotel) {
            _vo.trainningHotelId = this.transferData.hotel.id;
            _vo.hotelRemark = this.transferData.hotel.remarks;
          }
          if (this.trainInfo.setting.includeMembershipFees) {
            _vo.membershipFeeId = this.transferData.fee.membershipFeeId;
            _vo.membershipFeeYear = this.transferData.fee.membershipFeeYear;
          }
          this.vo = _vo;
          this.getCalculateEntryOrder(_vo);
        }
      }
    }
  },
  methods: {
    getCalculateEntryOrder (vo) {
      this.pageLoading = true;
      this.nextLoading = true;
      api_POST_TrainTrainningEntryCalculateEntryOrder(vo)
        .then(
          res => {
            this.pageLoading = false;
            this.nextLoading = false;
            this.calculateEntryOrder = res;
            this.charges = res.charges || [];
            this.calculateEntryOrderSuccess = true;
          }
        )
        .catch(
          error => {
            this.pageLoading = false;
            this.nextLoading = false;
            this.$message({
              message: `费用获取失败 ${error.error.message}`,
              type: 'error',
              showClose: true
            });
          }
        );
    },
    // 点击支付按钮
    clickPay () {
      this.judgeIsShowDialogVisibleForPay();
    },
    // 判断是否显示支付方式选择弹窗
    judgeIsShowDialogVisibleForPay () {
      // 请注意代码顺序不可调整
      const _setOnline = this.calculateEntryOrder.isSetOnline; // 设置了线上支付
      const _setOffline = this.calculateEntryOrder.isSetOffline; // 设置了线下支付

      // 当同时设置了线上与线下支付时，弹窗让用户选择支付方式
      if (_setOnline && _setOffline) {
        this.dialogVisibleForPay = true;
        return;
      }

      // 仅设置了线上支付
      if (_setOnline) {
        this.clickPayOnline();
        return;
      }

      // 仅设置了线下支付
      if (_setOffline) {
        this.clickPayOffline();
        return;
      }
    },
    // 线上支付
    clickPayOnline () {
      this.isOnlinePayment = true; // 是否是线上订单
      this.vo.isOnlinePayment = true;
      this.submitOrder();
    },
    // 线下支付
    clickPayOffline () {
      this.isOnlinePayment = false; // 是否是线上订单
      this.vo.isOnlinePayment = false;
      this.submitOrder();
    },
    // 提交订单
    submitOrder() {
      this.modalPayLoding = true;
      api_POST_TrainTrainningEntrySubmitOrder(this.vo)
        .then(
          res => {
            this.orderNo = res.orderNo;
            if (this.isOnlinePayment) {
              // 如果是线上支付
              this.payment(res.orderNo);
            } else {
              // 线下支付，展示获取订单信息，展示收款账户信息
              this.getOrderDetails(res.orderNo);
            }
          }
        )
        .catch(
          error => {
            this.modalPayLoding = false;
            this.$message({
              message: `订单创建失败！${error.error.message}`,
              type: 'error',
              showClose: true
            });
            console.log(error);
          }
        );
    },
    // 去支付
    payment(orderNo) {
      if (orderNo) {
        const _origin = window.location.origin;
        // const _pathname = window.location.pathname;
        const _pathname = '/game.html';
        const _orderUrl = '#/myCenter/order/main';
        const url = _origin + _pathname + _orderUrl;
        this.orderParameterQO.OrderNo = orderNo;
        this.orderParameterQO.ReturnUrl = url; // 支付成功后跳转的地址
        api_GET_TradePayOrderParameter(this.orderParameterQO)
          .then(res => {
            this.$refs.pay_params.value = res.parameter.replace(/\s*/g, '');
            this.$refs.form.submit();
          });
      }
    },
    // 获取订单详情，用于线下支付展示收款账户信息
    getOrderDetails (orderNo) {
      api_GET_TradePersonalOrderCollectionCode({ orderNo: orderNo })
        .then(
          res => {
            console.log('getOrderDetails -> res', res);
            res._orderNo = orderNo;
            this.offlineData = res;
            this.offlineDialogVisible = true;
          }
        )
        .catch(
          error => {
            this.modalPayLoding = false;
            this.$message({
              message: `订单详情获取失败！${error.error.message}`,
              type: 'error',
              showClose: true
            });
            console.log('getOrderDetails -> error', error);
          }
        );
    },
    // 跳转到订单中心
    jumpToOrderCenter () {
      // 线下支付,直接去订单中心
      var a = document.createElement('a');
      var event = new MouseEvent('click');
      const _origin = window.location.origin;
      const _path = '/game.html#/myCenter/order/main';
      const url = _origin + _path + '?out_trade_no=' + this.orderNo;
      a.href = url;
      a.target = '_self';
      a.dispatchEvent(event);
    },
    // 格式化货币格式 （分）
    formatMoney (num) {
      if (typeof num === 'number' && !Number.isNaN(num)) {
        // num 是数字类型 且不是 NaN
        let strNum = String(num); // 金额文本类型
        if (num >= 0) {
          strNum = strNum.padStart(3, '0'); // 用0填充保证最小三位数
          return strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        } else {
          const _mark = strNum.slice(0, 1); // 负号
          const _noMark = strNum.slice(1); // 无负号数值
          strNum = _noMark.padStart(3, '0'); // 用0填充保证最小三位数
          return _mark + strNum.slice(0, -2) + '.' + strNum.slice(-2); // 金额拼接
        }
      } else {
        return '';
      }
    },
    // 将元转化为分
    yuanToFen(moneyStr) {
      const _moneyStr = String(moneyStr);
      const yuan = Number(_moneyStr.split('.')[0]) || 0;
      const fen = Number(_moneyStr.split('.')[1]) || 0;
      return yuan * 100 + fen;
    },
    onPrevStep () {
      this.$emit('onPrevStep');
    },
    onNextStep () {
      this.$emit('onNextStep');
    }
  }
};
</script>

<style>
  .train_step_fee .el-table,
  .train_step_fee .el-table__body-wrapper {
    min-height: auto;
  }
  .train_step_fee .gl_table_noBorder.el-table {
    border: none !important;
  }
</style>

<style lang="scss" scoped>
  .table_bottom {
    text-align: right;
    font-size: 14px;
    line-height: 22px;
    font-weight: 500;
    color: rgba(0, 0, 0, 0.85);
    line-height: 22px;

    .price {
      min-width: 130px;
      display: inline-block;
      vertical-align: middle;
    }
    .count {
      margin-right: 40px;
      display: inline-block;
      vertical-align: middle;
    }
    .price_color {
      color: #DC1D1D;
    }
  }

  .order_summary {
    line-height: 22px;
    font-size: 16px;
    font-weight: 500;
    color: #353434;
  }
  .order_summary_label {
    display: inline-block;
    min-width: 65px;
    margin-right: 10px;
  }
  .order_summary_price {
    display: inline-block;
    // min-width: 100px;
    text-align: right;
  }
  .gl_color_total {
    color: #DC1D1D;
  }

  .pay_type_list {
    display: flex;
    justify-content: space-around;
  }
  .pay_type_item {
    width: 260px;
    height: 84px;
    padding: 0 50px;
    text-align: right;
    color: #fff;
    font-size: 24px;
    line-height: 84px;
    cursor: pointer;
  }
  .pay_type_online {
    background-image: url('../../../../assets/images/pay/online.png');
    background-repeat: no-repeat;
  }
  .pay_type_offline {
    background-image: url('../../../../assets/images/pay/offline.png');
    background-repeat: no-repeat;
  }

  .no_hotel {
    padding-top: 20px;
    text-align: center;
    font-size: 14px;
    line-height: 26px;
    color: #3a3939
  }
</style>
